package com.example.luozizhao.eprxdemo.presenter;

import android.Manifest;
import android.os.Build;
import android.text.TextUtils;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PhoneUtils;
import com.example.luozizhao.eprxdemo.base.presenter.BasePresenter;
import com.example.luozizhao.eprxdemo.http.RetrofitHelper;
import com.example.luozizhao.eprxdemo.net.request.UserLoginReqBean;
import com.example.luozizhao.eprxdemo.net.response.GetNounceRespBean;
import com.example.luozizhao.eprxdemo.net.response.login.UserLoginRespBean;
import com.example.luozizhao.eprxdemo.ui.activity.LoginActivity;
import com.example.luozizhao.eprxdemo.utils.AppPhoneUtils;
import com.example.luozizhao.eprxdemo.utils.EncodeUtil;
import com.example.luozizhao.eprxdemo.utils.RxUtils;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;


import javax.inject.Inject;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by luozizhao on 2018/5/16.
 */

public class LoginPresenter extends BasePresenter<LoginActivity> {


    private static final String TAG = "LoginPresenter";

    public int a = 0;

    @Inject
    public LoginPresenter(int a) {
        this.a = a;
    }


    public void login(String user, String pw) {

        if (TextUtils.isEmpty(user.trim()) || TextUtils.isEmpty(pw.trim())) {
            mView.showErrorMsg("用户名密码不能为空");
            return;
        }

        RetrofitHelper.getInstance().getTattedCode().compose(RxUtils.rxSchedulerHelper())
                .doOnNext(new Consumer<GetNounceRespBean>() {
                    @Override
                    public void accept(GetNounceRespBean getNounceRespBean) throws Exception {
                        LogUtils.d(TAG, "获取会话码成功: tattedCode:" + getNounceRespBean.data);
                    }
                }).observeOn(Schedulers.io()).flatMap(new Function<GetNounceRespBean, ObservableSource<?>>() {
            @Override
            public ObservableSource<UserLoginRespBean> apply(GetNounceRespBean getNounceRespBean) throws Exception {
                LogUtils.d(TAG, "tattedCode:" + getNounceRespBean.data);
                com.example.luozizhao.eprxdemo.net.request.UserLoginReqBean userLoginReqBean = new UserLoginReqBean();

                String userName = user;
                String password = pw;
                password = EncodeUtil.encode_MD5(userName + EncodeUtil.encode_MD5(password) + getNounceRespBean.data);
                String tattedCode = getNounceRespBean.data;
                String loginClient = "android";
                String deviceId = PhoneUtils.getIMEI();
                String deviceNumber = AppPhoneUtils.getDevPhoneNumber();
                String appVersion = AppUtils.getAppVersionName();
                String osVersion = "android" + Build.VERSION.RELEASE;
                String osModel = Build.MODEL;
                String osManufacturer = Build.BRAND;

                userLoginReqBean.appVersion = appVersion;
                userLoginReqBean.bindKey = "";
                userLoginReqBean.deviceId = deviceId;
                userLoginReqBean.deviceNumber = deviceNumber;
                userLoginReqBean.loginClient = loginClient;
                userLoginReqBean.osManufacturer = osManufacturer;
                userLoginReqBean.osModel = osModel;
                userLoginReqBean.osVersion = osVersion;
                userLoginReqBean.tattedCode = tattedCode;
                userLoginReqBean.password = password;
                userLoginReqBean.userName = userName;
                Map<String, String> sendData = getSendData(userLoginReqBean);
                LogUtils.d(TAG, "执行login(params)");
                return RetrofitHelper.getInstance().login(sendData);
            }
        }).subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    UserLoginRespBean bean = (UserLoginRespBean) response;
                    if (bean.getCode() == 0) {
                        mView.loginSuccess();
                        LogUtils.d(TAG, "登陆成功 : user:" + bean.toString());
                    } else {
                        mView.showSnackErrorMsg(mView,bean.getDesc());
                        return;
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.d(TAG, "登陆失败");
                        mView.showSnackErrorMsg(mView,"登录失败,请检查网路");
                    }
                });
    }


    public <T> Map<String, String> getSendData(T beanClass) {
        if (beanClass == null) {
            return null;
        }
        try {
//			T bean = beanClass;
            Class<? extends Object> clazz = beanClass.getClass();

            Map<String, String> paramsMap = new HashMap<String, String>();
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                String name = field.getName();
                Object filedValue = field.get(beanClass);

                if (filedValue != null && !"".equals(filedValue)) {
                    paramsMap.put(name, filedValue.toString());
                }
            }
            return paramsMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void requestPermissions() {
        RxPermissions rxPermission = new RxPermissions(mView);
        rxPermission
                .requestEach(/*Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_CALENDAR,
                        Manifest.permission.READ_CALL_LOG,
                        Manifest.permission.READ_CONTACTS,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_SMS,
                        Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAMERA,
                        Manifest.permission.CALL_PHONE,
                        Manifest.permission.SEND_SMS,*/
                        Manifest.permission.READ_PHONE_STATE
                )
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            // 用户已经同意该权限
                            LogUtils.d(TAG, permission.name + " is granted.");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            LogUtils.d(TAG, permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            LogUtils.d(TAG, permission.name + " is denied.");
                        }
                    }
                });
    }


}
